#!/usr/bin/python3.5
# -*- coding utf-8

from selenium import webdriver
import os

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
browser = webdriver.Chrome(chrome_options=chrome_options)


def write_book(content):
    file_path = '/Users/kaiji/Desktop/'
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    file_name = '三寸人间.txt'
    file_path_name = file_path + file_name
    with open(file_path_name, 'a', encoding='utf-8') as f:
        f.write(content + '\n\n')
        f.close()


def get_book_content(url):
    browser.get(url)
    # browser.find_element_by_link_text('章节目录').send_keys(Keys.ENTER)
    title = browser.find_element_by_class_name("bookname").find_element_by_tag_name("h1").text
    print('title===>', title)
    write_book(title)
    content = browser.find_element_by_id("content").text
    remove_content = browser.find_element_by_css_selector('#content > p').text
    content = content.replace(remove_content, '')
    write_book(content)
    href = browser.find_element_by_class_name('bottem1').find_elements_by_tag_name("a")[3].get_attribute("href")
    if href is not None:
        get_book_content(href)
    else:
        pass


get_book_content("http://www.xbiquge.la/10/10489/4534454.html")

'''
1. 获取这本书的目录
2. 点击目录地址
3.1 获取章节头部
3.2 获取章节内容
4. 写入到文件中去
'''
